package cc.sunni.rabbitmqdelayedmessagedemo.component;

import cc.sunni.rabbitmqdelayedmessagedemo.config.DelayedMessageConfig;
import cc.sunni.rabbitmqdelayedmessagedemo.entity.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DelayedMessageSender {
    private final Logger log = LoggerFactory.getLogger(DelayedMessageSender.class);

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send(String msg, Integer delaySeconds) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("发送时间:" + sf.format(new Date()));

        rabbitTemplate.convertAndSend(DelayedMessageConfig.EXCHANGE_NAME, DelayedMessageConfig.QUEUE_NAME, msg, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 给消息设置延迟毫秒值
                message.getMessageProperties().setHeader("x-delay", delaySeconds * 1000);
                return message;
            }
        });
    }

    public void send(Order order, Integer delaySeconds) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("发送时间:" + sf.format(new Date()));

        rabbitTemplate.convertAndSend(DelayedMessageConfig.EXCHANGE_NAME, DelayedMessageConfig.QUEUE_NAME, order, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 给消息设置延迟毫秒值
                message.getMessageProperties().setHeader("x-delay", delaySeconds * 1000);
                return message;
            }
        });
    }
}